import io
import string
import random

from django.contrib.auth.models import User, Group
from django.http import HttpResponse
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet, ViewSet

from celery_tasks.email.tasks import send_mail_task
from config.dbs.redisConfig import LOGIN_KEY_TEMPLATE, EXPIRE_TIME
from student import models
from student.serializers.classStudentSystemSerializer import StudentSerializer, ClassesSerializer, CreateUserSerializer
from student.utils import MyPermission
from utils.verifyUtil import ImageVerify


class StudentViewSet(ModelViewSet):
    queryset = models.Student.objects.filter(is_delete=False, classes__is_delete=False)
    serializer_class = StudentSerializer


class ClassesViewSet(ModelViewSet):
    queryset = models.Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer


class ImageVerifyView(View):
    def get(self, request, uuid):
        """获取图片验证码"""
        print(uuid)
        imageVerify = ImageVerify()
        image, code = imageVerify.verify_code()
        print(code)

        img_bytes = io.BytesIO()
        image.save(img_bytes, format='PNG')
        image_bytes = img_bytes.getvalue()

        # 将客户端标识UUID作为key，将验证码答案作为value
        cache = get_redis_connection(alias='verify_codes')
        cache.set(LOGIN_KEY_TEMPLATE % uuid, code, EXPIRE_TIME)

        return HttpResponse(image_bytes, content_type='image/png')


class ClassesMemberViewSet(GenericViewSet):
    permission_classes = [MyPermission]
    serializer_class = CreateUserSerializer

    def add_member(self, request, pk):
        # 获取班级
        try:
            classes = models.Classes.objects.get(id=pk)
        except models.Classes.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        # 判断该成员是否已属于班级
        username = request.data.get('username')
        member = classes.member.filter(username=username)
        if member:
            # 属于返回提示
            return Response({'msg': '该成员已加入该班级'})
        # 不属于，判断是否注册，是否存在此用户
        user = User.objects.filter(username=username).first()
        if user:
            # 存在，添加到该班级
            classes.member.add(user)
            return Response(self.get_serializer(user).data)

        # 不存在，注册用户，并添加学生身份，添加到该班级
        userserializer = self.get_serializer(data=request.data)
        userserializer.is_valid(raise_exception=True)
        email = request.data['email']
        first_name = request.data['first_name']
        user = User(username=username, email=email, first_name=first_name)
        # 生成初始化密码
        source = string.ascii_letters + string.digits
        password = ''.join(random.sample(source, 6))
        user.set_password(password)
        user.save()
        # 添加学生身份
        group = Group.objects.get(id=1)
        group.user_set.add(user)

        # 添加到班级
        classes.member.add(user)
        # 使用celery发送短信验证码
        send_mail_task.delay(email, username, password, classes.name)

        return Response(userserializer.data)
